package com.zxy.day0624_util.utils;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

public class PDFUtils {
    private static Font DEFAULT_FONT;

    public PDFUtils() {
    }

    public static <T> void table2PDF(String file, String title, Font font, String imgPath, List<String> headers, List<String> props, List<T> data) {
        try {
            Document document = new Document(PageSize.A4);
            PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            if (font == null) {
                font = DEFAULT_FONT;
            }

            if (StringUtil.hasText(title)) {
                writeTitle(title, document, font);
            }

            PdfPTable table = new PdfPTable(headers.size());
            writeHeaders(font, headers, table);
            writeData(font, props, data, table);
            document.add(table);
            if (StringUtil.hasText(imgPath)) {
                writeImage(imgPath, document);
            }

            document.close();
        } catch (Exception var9) {
            System.out.println("pdf生成失败");
            var9.printStackTrace();
        }

        System.out.println("PDF生成成功");
    }

    public static boolean pdf2png(String pdfFile, String pngFile) {
        System.out.println("开始pdf生成png图片");

        try {
            PDDocument pdfDocment = PDDocument.load(new File(pdfFile));
            int pages = pdfDocment.getNumberOfPages();
            PDFRenderer pdfRenderer = new PDFRenderer(pdfDocment);

            for(int i = 0; i < pages; ++i) {
                BufferedImage image = pdfRenderer.renderImage(i, 2.5F);
                ImageIO.write(image, "PNG", new File((new StringBuffer(pngFile)).insert(pdfFile.lastIndexOf("."), "_" + i).toString()));
                System.out.println("生成成功");
            }

            return true;
        } catch (Exception var7) {
            var7.printStackTrace();
            System.out.println("转化失败");
            return false;
        }
    }

    private static <T> void writeData(Font font, List<String> props, List<T> data, PdfPTable table) throws NoSuchFieldException, IllegalAccessException {
        Iterator var4 = data.iterator();

        while(var4.hasNext()) {
            T t = (T) var4.next();
            Iterator var6 = props.iterator();

            while(var6.hasNext()) {
                String prop = (String)var6.next();
                Field field = t.getClass().getDeclaredField(prop);
                if (Objects.nonNull(field)) {
                    field.setAccessible(true);
                    Object value = field.get(t);
                    if (Objects.nonNull(value)) {
                        table.addCell(new PdfPCell(new Phrase(value.toString(), font)));
                    } else {
                        table.addCell(new PdfPCell(new Phrase("", font)));
                    }
                } else {
                    table.addCell(new PdfPCell(new Phrase("", font)));
                }
            }
        }

    }

    private static void writeHeaders(Font font, List<String> headers, PdfPTable table) {
        headers.forEach((item) -> {
            table.addCell(new PdfPCell(new Phrase(item, font)));
        });
    }

    private static void writeImage(String imgPath, Document document) throws BadElementException, MalformedURLException, IOException, DocumentException {
        Image image = Image.getInstance(imgPath);
        image.setAlignment(1);
        image.scalePercent(40.0F);
        document.add(image);
    }

    private static void writeTitle(String title, Document document, Font font) throws Exception {
        Paragraph paragraph = new Paragraph(title, font);
        paragraph.setAlignment(1);
        paragraph.setIndentationLeft(12.0F);
        paragraph.setIndentationRight(12.0F);
        paragraph.setFirstLineIndent(24.0F);
        paragraph.setLeading(20.0F);
        paragraph.setSpacingBefore(5.0F);
        paragraph.setSpacingAfter(10.0F);
        document.add(paragraph);
    }

    /**
     * 获取字体
     * @param winPath
     * @param linuxPath
     * @return
     */
    public static Font getFont(String winPath, String linuxPath) {
        String fontPath = System.getProperty("os.name").toLowerCase().contains("windows") ? winPath : linuxPath;

        try {
            return new Font(BaseFont.createFont(fontPath, "Identity-H", true));
        } catch (Exception var4) {
            var4.printStackTrace();
            System.out.println("获取失败");
            return DEFAULT_FONT;
        }
    }

    public static void main(String[] args) throws DocumentException, IOException {
        Font font = getFont("C:\\Windows\\Fonts\\simhei.ttf", "/tmp/simkai.ttf");
        System.out.println(font);
    }

    static {
        try {
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
            DEFAULT_FONT = new Font(baseFont);
        } catch (Exception var1) {
            var1.printStackTrace();
        }

    }



}
